﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
using CloudShot.Interfaces;
using CloudShot.Utils;

namespace CloudShot.Services
{
  internal class ClipboardService : IClipboardService
  {
    private const int RetryTimes = 5;
    private const int RetryDelay = 400;

    public void Clear()
    {
      Clipboard.Clear();
    }

    public void SetImage(Image image)
    {
      if (image == null)
        throw new ArgumentNullException("image");

      var dataObject = new DataObject();
      SetImageWithDib(dataObject, image);
      Clipboard.SetDataObject(dataObject, true, RetryTimes, RetryDelay);
    }

    public void SetText(string text)
    {
      if (string.IsNullOrEmpty(text))
        throw new ArgumentNullException("text");

      var dataObject = new DataObject();
      if (!string.IsNullOrEmpty(text))
        dataObject.SetText(text);

      Clipboard.SetDataObject(dataObject, true, RetryTimes, RetryDelay);
    }

    //https://issues.apache.org/ooo/show_bug.cgi?id=85661
    private static void SetImageWithDib(DataObject dataObject, Image image)
    {
      using (var bitmapStream = new MemoryStream())
      {
        var dibStream = new MemoryStream();//NOTE: don't close stream! It should be open when dataObject will be set to clipboard

        image.Save(bitmapStream, ImageFormat.Bmp);

        byte[] bitmapData = bitmapStream.GetBuffer();
        dibStream.Write(bitmapData, 14, (int)(bitmapStream.Length - 14));
        bitmapStream.Position = 0;

        dataObject.SetData(DataFormats.Bitmap, image);
        dataObject.SetData(DataFormats.Dib, dibStream); //it's necessary for possibility to paste image in other applications        
      }
    }
  }
}